package com.polaris.live.widget.refresh

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import androidx.recyclerview.widget.RecyclerView
import com.polaris.live.R
import kotlin.math.abs
import kotlin.math.atan2

/**
 * XRecyclerView
 *
 * @author Created by lucas on 2024/4/8 09:25
 */
open class XRecyclerView(context: Context, attrs: AttributeSet? = null) : RecyclerView(context, attrs) {

    private val mTouchSlop = ViewConfiguration.get(context).scaledTouchSlop

    private var mViewPagerNested = false
    private var mDownX = 0
    private var mDownY = 0

    private var mDisallowIntercept = false

    init {
        //滑动嵌套
        if (attrs != null) {
            val typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.XRecyclerView)

            val viewPagerNested = typedArray.getBoolean(R.styleable.XRecyclerView_viewPagerNested, false)
            setViewPagerNested(viewPagerNested)

            typedArray.recycle()
        }
    }

    /**
     * 设置是否为viewpager嵌套
     */
    fun setViewPagerNested(viewPagerNested: Boolean) {
        this.mViewPagerNested = viewPagerNested
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (mViewPagerNested) {
            when (ev.action) {
                MotionEvent.ACTION_DOWN -> {
                    mDownX = ev.x.toInt()
                    mDownY = ev.y.toInt()

                    parent.requestDisallowInterceptTouchEvent(true)
                }
                MotionEvent.ACTION_MOVE -> {
                    val moveX = ev.x.toInt()
                    val moveY = ev.y.toInt()
                    val deltaX = abs(moveX - mDownX)
                    val deltaY = abs(moveY - mDownY)

                    val angle = atan2(deltaY.toDouble(), deltaX.toDouble()) * (180 / Math.PI)

                    if (deltaX > deltaY && deltaX > mTouchSlop && angle <= MIN_ANGLE) {
                        if (mDisallowIntercept) {
                            parent.requestDisallowInterceptTouchEvent(true)
                        } else {
                            parent.requestDisallowInterceptTouchEvent(false)
                        }

                    } else {
                        parent.requestDisallowInterceptTouchEvent(true)
                    }
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    mDisallowIntercept = false
                    parent.requestDisallowInterceptTouchEvent(true)
                }
            }
        }

        return super.dispatchTouchEvent(ev)
    }

    override fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
        this.mDisallowIntercept = disallowIntercept
        super.requestDisallowInterceptTouchEvent(disallowIntercept)
    }

    companion object {

        private const val MIN_ANGLE = 30
    }
}